package com.tencent.wuyanzu.websocket;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.alibaba.fastjson.JSONObject;



@ServerEndpoint("/ws/group")

public class WebSocket {
	
	private static HashMap<String,Group> groups = new HashMap<String,Group>();
	private static Queue<String> available = new ConcurrentLinkedQueue<String>();
	private final static int UPPER_LIMIT = 9999;      //总共提供的并发groupID上线
	
	static{
		String path = WebSocket.class.getResource("").getPath();  
		String webAppPath = path.substring(0, path.toUpperCase().lastIndexOf("WEB-INF/")).replaceAll("%20", " ");  
		System.setProperty("webapp",webAppPath + "logs/mini.log");
		try {
			PropertyConfigurator.configure(WebSocket.class.getClassLoader().getResource("").toURI().getPath()+"/mylog4j.properties");
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		for(int i = 1000 ; i <= UPPER_LIMIT ; i++ ){
			available.add(String.valueOf(i));
		}
	}
	
	private final Logger logger = Logger.getLogger(this.getClass());
	private Session session = null;
    private Group grp = null;
	
	@OnMessage
	public void onMessage(String message, Session session) throws IOException, InterruptedException {
		JSONObject job = JSONObject.parseObject(message);
		
		if(!job.containsKey("type")){
			logger.error("json format error! no type");
			return;
		}
 		
		String type = job.getString("type");
		
		if(type.equals("launch")){
			String id = available.poll();
			grp = new Group(id);
			this.session = session;
			grp.addSocket(this);
			groups.put(id, grp);
			grp.broadcast();
			return;
	
			
		}else if(type.equals("join")){
			String gid = job.getString("groupID");
			grp = groups.get(gid);
			this.session = session;
			if(!grp.doAgree()){
				grp.addSocket(this);
				grp.broadcast();
			}else{
				JSONObject ret = new JSONObject();
				ret.put("msg","agree");
				send(ret.toJSONString());
			}
		}
		else if(type.equals("start")){
			grp.start();
			
		}
		else if(type.equals("oppose")){
			String rid = job.getString("rid");
			if(!grp.doAgree()){
				grp.oppose(rid);
				grp.broadcast();
			}
			
		}else{
			logger.error("json format error! type error");
		}
		
	}

	@OnOpen
	public void onOpen(Session s) {
		
		System.out.println(" connection connected ");
	}

	@OnClose
	public void onClose(Session s) {
		grp.removeSoeckt(this);
		if(!grp.isEmpty()){
			grp.broadcast();
		}else{
			available.add(grp.getID());
			grp.getTimer().cancel();
			groups.remove(grp);
		}
		System.out.println(" connection closed ");
	}
	
	public void send(String message){
		try {
			session.getBasicRemote().sendText(message);
		} catch (IOException e) {
			logger.error(e.getMessage());
		}
	}
}
